package it.canraid.control;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;

public class NetworkAgent extends CAgent {
    public final int CODE_SIZE_QUEUE = 100;
    public final int CODE_OUTPUT = 101;
    public final int CODE_NAME;
    public final String LABEL_NAME = getClass().getName();
    private final String URL_NETWORK;
    private Context context = null;
    private Handler[] handlers = null;

    public NetworkAgent(Context context, String URL_NETWORK) {
	super(1000);
	this.context = context;
	this.URL_NETWORK = URL_NETWORK;
	this.CODE_NAME = hashCode();
    }

    public int getAgentName() {
	return CODE_NAME;
    }

    protected boolean __setup() {
	ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
	if (networkInfo != null && networkInfo.isConnected()) {
	    return true;
	}
	return false;
    }

    protected boolean __loop() {
	byte[] bufferInput = new byte[0];
	int bytesBufferInput = bufferInput.length;
	HttpURLConnection connection = null;
	BufferedReader streamIn = null;
	DataOutputStream streamOut = null;

	try {
	    handlers = __getHandlersToNotifies();
	    int sizeBufferOutput = getQueueLength();

	    for (int h = 0; h < handlers.length; h++) {
		handlers[h].obtainMessage(CODE_NAME, IHandlerCommunication.ACTION_FROM_AGENT, CODE_SIZE_QUEUE, sizeBufferOutput).sendToTarget();
	    }

	    URL url = new URL(URL_NETWORK);
	    connection = (HttpURLConnection) url.openConnection();
	    connection.setReadTimeout(5000 /* milliseconds */);
	    connection.setConnectTimeout(7000 /* milliseconds */);
	    connection.setDoOutput(true);
	    connection.setRequestMethod("POST");
	    connection.connect();

	    streamOut = new DataOutputStream(connection.getOutputStream());

	    // Write to URL
	    if (sizeBufferOutput > 0) {
		byte[] data = __getCopyBufferOutput(false);
		String encode = Uri.encode(new String(data));

		streamOut.write(encode.getBytes());
		streamOut.flush();
		__commitCopyBufferOutput(data.length);
	    }

	    // Read to URL

	    streamIn = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	    String inputLine;
	    String text = "";
	    while ((inputLine = streamIn.readLine()) != null)
		text = text + inputLine;

	    bufferInput = text.getBytes();

	    bytesBufferInput = bufferInput.length;

	    if (bytesBufferInput > 0) {
		String decode = Uri.decode(new String(bufferInput));
		if (!decode.trim().equals("")) {
		    bufferInput = decode.getBytes();

		    for (int h = 0; h < handlers.length; h++) {
			handlers[h].obtainMessage(CODE_NAME, IHandlerCommunication.ACTION_FROM_AGENT, CODE_OUTPUT, bufferInput).sendToTarget();
		    }
		}
	    }
	} catch (Exception e) {
	    return false;
	} finally {
	    try {
		if (streamIn != null)
		    streamIn.close();
	    } catch (IOException e2) {
	    }

	    try {
		if (streamOut != null)
		    streamOut.close();
	    } catch (IOException e2) {
	    }

	    if (connection != null)
		connection.disconnect();

	    connection = null;
	    streamIn = null;
	    streamOut = null;
	}
	return true;
    }

    public void close() {
	stopPolling();

    }

    protected boolean __implementMyHandler(Message msg) {
	return false;
    }

}
